<?php
// 应用公共文件
use think\facade\Cache;
use think\facade\Db;
use think\facade\Event;
use think\facade\Request;
use frank\utils\helper\ArrayHelper;

if (!function_exists('sysconf')) {
	/**
     * 配置系统参数
     * @param string $name 参数名称
     * @param boolean $value 无值为获取
     * @return string|boolean
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    function sysconf($name, $value = null)
    {
        static $data = [];
        list($field, $raw) = explode('|', "{$name}|");
        if ($value !== null) {
            Cache::delete("system_config", $data);
            list($row, $data) = [['name_field' => $field, 'value' => $value], []];
            $wh = Db::name('system_config')->where('name_field','=',$field)->find();
            return Db::name('system_config')->where($wh)->save($row);
        }
        if (empty($data)) {
            $data = Cache::get('system_config');
            if (empty($data)) {
                $data = Db::name('system_config')->column('value','name_field');
                Cache::set("system_config", $data);
            }
        }
        if (isset($data[$field])) {
            if (empty($raw) || strtolower($raw) === 'raw') {
                return $data[$field];
            } elseif (strtolower($raw) === 'json') {
                return ArrayHelper::objectToArray(json_decode($data[$field]));
            } 
        } else {
            return '';
        }
    }   
}   
/**
 * 事件
 */
if (!function_exists('event')) {
    function event($event, $args = [], $once = true)
    {
        $res = Event::trigger($event, $args);
        if (is_array($res)) {
            $res = array_filter($res);
            sort($res);
        }
        //只返回一个结果集
        if ($once) {
            return isset($res[ 0 ]) ? $res[ 0 ] : [];
        }
        return $res;
    }
}

if (!function_exists('formatDatetime')) {
    /**
     * 日期格式标准输出
     * @param string $datetime 输入日期
     * @param string $format 输出格式
     * @return false|string
     */
    function formatDatetime($datetime, $format = 'Y-m-d H:i:s')
    {
        if (empty($datetime)) return '-';
        if (is_numeric($datetime)) {
            return date($format, $datetime);
        } else {
            return date($format, strtotime($datetime));
        }
    }
}  

if (!function_exists('_strtotime')) {
    function _strtotime($datetime)
    {
        if (!is_numeric($datetime)) {
            return strtotime($datetime);
        }else{
            return $datetime;
        }
    }
}  

/**
 * 日记
 */
if (!function_exists('_trace')) {
    function _trace($traceType, $message = '', $type = 'error')
    {
        trace([
            'type' => $traceType,
            'message' => $message,
            'param' => \request()->param()
        ],$type);
    }
}


if (!function_exists('baseUrl')) {
    function baseUrl()
    {
        static $baseUrl = '';
        $request = Request::instance();
        return $request->domain();
    }
}